<template>
    <div class="repair">
        <van-form
            show-error
            scroll-to-error
            label-width="25vw"
            @submit="onSubmit"
            @failed="onFailed" 
        >
            <MyTitle>使用人信息</MyTitle>
            <van-field 
                v-model="formData.gsy_ex1" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex1" 
                label="使用人姓名"
                placeholder="使用人姓名" 
                :rules="[{ required: true, message: '请填写使用人姓名' }]"
            />
            <MyTitle>祭祀信息</MyTitle>
            <FieldPopupDatePicker 
                v-model:field="formData.gsy_dat1" 
                :required="true"
                :minDate="new Date()"
                name="gsy_dat1" 
                label="祭扫日期" 
                :readonly="isReadonly"
            />
            <FieldPopupTimePicker 
                v-model:field="formData.gsy_dat2" 
                :required="true"
                :minTime="minTime"
                name="gsy_dat2" 
                label="祭扫时间" 
                :readonly="isReadonly"
            />

            <van-field 
                v-model="formData.gsy_ex4" 
                :readonly="isReadonly"
                type="number"
                required
                center
                name="gsy_ex4" 
                label="祭扫人数"
                placeholder="祭扫人数" 
                :rules="[{ required: true, message: '请填写祭扫人数' }]"
            />
            <!-- <van-field 
                v-model="formData.gsy_ex100" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex100" 
                label="墓地位置"
                placeholder="墓地位置" 
                :rules="[{ required: true, message: '请填写墓地位置' }]"
            /> -->
            <FieldPopupCascader 
                :field="gsy_ex100"
                @update:field="gsy_ex100Change"
                name="gsy_ex100" 
                label="墓区" 
                :options="columns1" 
                confirmType="selectedOptions"
                :readonly="isReadonly" 
            />
            
            <FieldPopupPicker 
                v-if="gsy_ex100"
                :field="gsy_mainid"
                @update:field="gsy_mainidChange"
                :required="true"
                name="gsy_mainid" 
                label="墓穴编号" 
                :columns="columns2" 
                confirmType="selectedOptions"
                :readonly="isReadonly" 
            />
            <MyTitle>预约人信息</MyTitle>
            <van-field 
                v-model="formData.gsy_ex2" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex2" 
                label="预约人姓名"
                placeholder="预约人姓名" 
                :rules="[{ required: true, message: '请填写预约人姓名' }]"
            >
                <template 
                    v-if="!isReadonly" 
                    #button
                >
                    <van-uploader 
                        v-model="dataArr.gsy_ex6" 
                        :readonly="isReadonly"
                        :preview-image="false" 
                        :before-delete="beforeDelete('gsy_ex6')" 
                        :before-read="beforeRead" 
                        :after-read="afterRead('gsy_ex6', true)"
                    >
                        <van-button 
                            size="small" 
                            icon="plus" 
                            type="primary" 
                            native-type="button"
                        >
                            拍照识别
                        </van-button>
                    </van-uploader>
                </template>
            </van-field>
            <van-field 
                v-model="formData.gsy_ex3" 
                :readonly="isReadonly"
                required
                center
                type="number" 
                maxlength="11"
                name="gsy_ex3" 
                label="联系电话"
                placeholder="联系电话" 
                :rules="[{ required: true, message: '请填写联系电话' },{ validator: isPhone, message: '请填写正确的联系电话' }]"
            />

            <van-field 
                v-model="formData.gsy_ex5" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex5" 
                label="预约人身份证"
                placeholder="预约人身份证" 
                :rules="[{ required: true, message: '请填写预约人身份证' },{ validator: validator3, message: '请填写正确的预约人身份证' }]"
            />
            <!-- <van-field 
                required
                readonly
                center
                name="gsy_ex6" 
                label="预约人身份证"
                :rules="[{ validator: validator2('gsy_ex6'), message: '请上传预约人身份证' }]"
            />
            <div class="uploader-box">
                <van-uploader 
                    v-model="dataArr.gsy_ex6" 
                    :readonly="isReadonly"
                    :max-count="1" 
                    upload-text="预约人身份证" 
                    :before-delete="beforeDelete('gsy_ex6')" 
                    :before-read="beforeRead" 
                    :after-read="afterRead('gsy_ex6')"
                    :deletable="!isReadonly"
                >
                    <template #default>
                        <img src="@/assets/uploader/uploader.png" />
                    </template>
                </van-uploader>
            </div> -->
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>
import { log } from 'console'
import { log } from 'console'

<script lang="ts" setup>
    import { ref, reactive, markRaw, onBeforeMount } from 'vue'
    import type { Ref, Raw } from 'vue'
    import { useRouter, useRoute } from 'vue-router'
    import { showDialog, showLoadingToast, closeToast, showFailToast  } from 'vant'
    import MyTitle from '@/components/MyTitle.vue'
    import FixedButton from '@/components/FixedButton.vue'
    import FieldPopupPicker from '@/components/FieldPopupPicker.vue'
    import FieldPopupDatePicker from '@/components/FieldPopupDatePicker.vue'
    import FieldPopupTimePicker from '@/components/FieldPopupTimePicker.vue'
    import FieldPopupCascader from '@/components/FieldPopupCascader.vue'
    
    import FieldPopupEsign from '@/components/FieldPopupEsign.vue'
    // import { useWeixinLogin3 } from '@/hooks'

    import { GmsmyuyApi, fileUploadBase64ExApi, idOrcApi, getAareaApi, getCemeteryApi } from '@/apis'
    import { isPhone, compressImg, isCardID, getSex, getAge } from '@/utils/utils.js'
    import { useStore } from '@/store'
    // 微信授权并且跳转到对应页面
    // useWeixinLogin3('sweepGraveAppointment')
    const router = useRouter()
    const route = useRoute()
    const store = useStore()
    const isReadonly: boolean = false
    const columns1: Ref<{
        text: string;
        value: string;
    }[]> = ref([
        // { text: '墓穴1', value: '墓穴1' },
        // { text: '墓穴2', value: '墓穴2' },
    ])
    const columns2: Ref<{
        text: string;
        value: string;
    }[]> = ref([
        // { text: '编号1', value: '编号1' },
        // { text: '编号2', value: '编号2' },
    ])
    onBeforeMount(async () => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        getAareaApi({
            iszj: 'N',
            time: new Date().getTime().toString(),
            company: '海陵区凤栖园智慧墓园系统'
        }).then(res => {
			let forFun = (arr2) => {
				arr2.forEach((item, index) => {
					item.value = item.id
					item.text = item.text
					if (item.child.length > 0) {
						item.children = item.child
						forFun(item.children)
					}
				})
			}
			forFun(res[0].child)
            columns1.value = res[0].child
        }).finally(() => {
            closeToast();
        })
        if (isReadonly) {
            console.log('...........')
            // 获取数据
            
        } else {
           
        }
    })
    const gsy_ex100Change = (val) => {
        gsy_ex100.value = ''
		val.forEach((item, index) => {
			if (val.length == (index+1)) {
				gsy_ex100.value += item.text
				formData.value.gsy_ex100 = item.value
			} else {
				gsy_ex100.value += item.text + '/'
			}
		})
        formData.value.gsy_mainid = ''
        gsy_mainid.value = ''

        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        columns2.value = []
        getCemeteryApi({
            areaId: formData.value.gsy_ex100,
            company: '海陵区凤栖园智慧墓园系统'
        }).then(res => {
            res.data[0]?.child.forEach((item, index) => {
                item.text = item.gm_ex6
                item.value = item.gm_id
            })
            columns2.value = res.data[0].child
        }).finally(() => {
            closeToast();
        })
    }
    const gsy_mainidChange = (val) => {
        gsy_mainid.value = val.text
        formData.value.gsy_mainid = val.value
    }

    let currentTime: any = new Date();
    currentTime.setHours(currentTime.getHours() + 1);
    console.log(currentTime.getHours().toString().padStart(2, '0'))
    console.log(currentTime.getMinutes().toString().padStart(2, '0'))
    currentTime = currentTime.getHours().toString().padStart(2, '0') + ':00:00'
    console.log(currentTime)
    // let minTime = currentTime
    const minTime: Ref<string> = ref(currentTime)
    const gsy_ex100: Ref<string> = ref('')
    const gsy_mainid: Ref<string> = ref('')

    const formData = ref({
        gsy_ex1: '',
        gsy_ex100: '',
        gsy_ex3: '',
        gsy_ex2: '',
        gsy_ex5: '',
        gsy_ex6: '',
        gsy_ex4: '',
        gsy_dat1: '',
        gsy_dat2: '',
        gsy_mainid: '',
        token: store.openid
    })
    const dataArr = reactive({
        gsy_ex6: [], //预约人身份证
    })
    
    // 照片数组验证
    const validator2 = (field) => {
        return val => {
            console.log(val)
            console.log(field)
            if (dataArr[field].length == 0 || !formData.value[field]) {
                return false
            } else {
                return true
            }
        }
    }
    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator3 = (val) => {
        if (isCardID(val)) {
            return false
        } else {
            return true
        }
    }
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',')
            arr.splice(detail.index, 1)
            formData.value[data] = arr.join(',')
            return true
        }
    }
    const beforeRead = (file) => {
        console.log(file)
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    }
    const afterRead = (imgField, isIdOrc = false) => {
        return file => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file )
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        }
    }
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done 
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file)
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64ExApi({
            data: obj,
            sCode: 'fhsxbyg'
        }).then(res => {
            // file.status = 'done';
            // file.message = '上传完成';
            console.log(res)

            if (imgField == 'gsy_ex6') {
                // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                if (dataArr[imgField].length > 1) {
                    dataArr[imgField].shift()
                }
                formData.value[imgField] = res[0].url
                // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                if (isIdOrc) {
                    idOrcApi({
                        img: obj
                    }).then(res => {
                        if (res.idcard_number_type == 1) {
                            let obj = res.words_result

                            if (imgField == 'gsy_ex6') {
                                formData.value.gsy_ex2 = obj['姓名'].words
                                formData.value.gsy_ex5 = obj['公民身份号码'].words
                            }
                        } else {
                            throw new Error('身份证验证失败')
                        }
                        file.status = 'done';
                        file.message = '上传完成';
                        
                    }).catch(err => {
                        console.log(err)
                        showFailToast('识别失败')
                        file.status = 'done';
                        file.message = '上传完成';
                    })
                } else {
                    file.status = 'done';
                    file.message = '上传完成';
                }

            } else {
                // formData.value[imgField] = res[0].url
                if (formData.value[imgField]) {
                    formData.value[imgField] = formData.value[imgField].concat(',', res[0].url)
                } else {
                    formData.value[imgField] = formData.value[imgField].concat(res[0].url)
                }
                file.status = 'done';
                file.message = '上传完成';
            }
            
        }).catch(err => {
            file.status = 'failed';
            file.message = '上传失败';
            console.log(dataArr[imgField])
            dataArr[imgField].pop()
            showFailToast('上传失败')
            console.log(err)
        })
    }






    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message
        })
    }
    const onSubmit = async (value) => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0
        });
        
        GmsmyuyApi({
            data: JSON.stringify(formData.value),
            gsy_company: store.company,
            gsy_dw: store.dw,
            // data: formData.value,
        }).then(res => {
            closeToast();
            if (res.status == '+OK') {
                showDialog({
                    title: '提示',
                    message: '提交成功！',
                }).then(() => {
                    router.push('/')                         
                });
            } else {
                showDialog({
                    title: '提示',
                    message: '网络异常，请稍后重试！',
                })
            }
            
        }).catch(err => {
            closeToast();
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            })
        })
    }
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .dnt-box {
        border-bottom: 1px solid #efefef;
    }
</style>